<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片裁剪</title>
    {:widget_st('cropper')}
    {:widget_st('layui','css')}
    {:widget_st('layui','js')}
    <style>
        .layui-container {
            max-width: 100%;
            padding: 15px;
        }
        #image-container, #preview {
            max-width: 100%;
            height: 400px;
            overflow: hidden;
        }
        #image, #preview-image {
            max-width: 100%;
            object-fit: contain;
        }
        .button-group {
            margin-top: 15px;
            text-align: center;
        }
        /*@media (max-width: 768px) {*/
        /*    .layui-col-md6 {*/
        /*        width: 50%;*/
        /*    }*/
        /*    #preview {*/
        /*        margin-top: 15px;*/
        /*    }*/
        /*}*/
    </style>
</head>
<body>
    <div class="layui-container">
        <div class="layui-row">
            <div class="layui-col-md12">
                <input type="file" id="file-input" accept="image/*">
            </div>
        </div>
        <div class="layui-row" style="margin-top: 15px;">
            <div class="layui-col-md6 layui-col-sm6" style="border: 1px solid #ccc;">
                <div id="image-container">
                    <img id="image" src="" alt="待裁剪的图片">
                </div>
            </div>
            <div class="layui-col-md6 layui-col-sm6">
                <div style="font-size: 30px;">预览</div>
                <div id="preview">
                    <img id="preview-image" src="" alt="预览图片">
                </div>
                <div class="layui-row button-group">
                    <button id="rotate-left" class="layui-btn layui-btn-primary">向左旋转</button>
                    <button id="rotate-right" class="layui-btn layui-btn-primary">向右旋转</button>
                    <button id="crop-button" class="layui-btn layui-btn-normal">确认裁剪</button>
                </div>
            </div>

        </div>

    </div>

    <script>
    layui.use(['layer'], function(){
        var layer = layui.layer;
        var cropper;
        var originalFileName;
        var isUploading = false; // 添加上传状态标志

        <?php if($url!=''){ ?>
            // 自动加载图片并初始化 Cropper
            (function() {
                function initImage() {
                    var imageElement = document.getElementById('image');
                    var fileInput = document.getElementById('file-input');

                    if (!imageElement || !fileInput) {
                        // 如果元素还不存在，等待一段时间后再次尝试
                        setTimeout(initImage, 100);
                        return;
                    }

                    imageElement.src = '{$url}';
                    originalFileName = '{$filename}';

                    imageElement.onload = function() {
                        if (cropper) {
                            cropper.destroy();
                        }
                        cropper = new Cropper(imageElement, {
                            viewMode: 1,
                            responsive: true,
                            restore: false,
                            crop: updatePreview
                        });

                        // 模拟文件选择
                        fetch('{$url}')
                            .then(response => response.blob())
                            .then(blob => {
                                var file = new File([blob], originalFileName, {type: "image/jpeg"});
                                var dataTransfer = new DataTransfer();
                                dataTransfer.items.add(file);
                                fileInput.files = dataTransfer.files;
                            })
                            .catch(error => {
                                console.error('获取图片失败:', error);
                                layer.msg('获取图片失败', {icon: 2});
                            });
                    };

                    imageElement.onerror = function() {
                        console.error('加载图片失败');
                        layer.msg('加载图片失败', {icon: 2});
                    };
                }

                // 修改 updatePreview 函数
                window.updatePreview = function() {
                    if (cropper && cropper.getCroppedCanvas()) {
                        var croppedCanvas = cropper.getCroppedCanvas();
                        document.getElementById('preview-image').src = croppedCanvas.toDataURL('image/jpeg');
                    }
                }

                // 立即执行初始化函数
                initImage();
            })();
        <?php } ?>

        function updatePreview() {
            if (cropper) {
                var croppedCanvas = cropper.getCroppedCanvas();
                document.getElementById('preview-image').src = croppedCanvas.toDataURL('image/jpeg');
            }
        }

        document.getElementById('file-input').addEventListener('change', function(e) {
            var file = e.target.files[0];
            originalFileName = file.name; // 保存原始文件名
            var reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('image').src = event.target.result;
                if (cropper) {
                    cropper.destroy();
                }
                cropper = new Cropper(document.getElementById('image'), {
                    viewMode: 1,
                    responsive: true,
                    restore: false,
                    crop: updatePreview
                });
            };
            reader.readAsDataURL(file);
        });

        document.getElementById('rotate-left').addEventListener('click', function() {
            if (cropper) {
                cropper.rotate(-10);
                updatePreview();
            }
        });

        document.getElementById('rotate-right').addEventListener('click', function() {
            if (cropper) {
                cropper.rotate(10);
                updatePreview();
            }
        });

        function generateRandomString(length) {
            var result = '';
            var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            for (var i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * characters.length));
            }
            return result;
        }

        document.getElementById('crop-button').addEventListener('click', function() {
            if (!cropper) {
                layer.msg('请先选择图片', {icon: 2});
                return;
            }
            if (isUploading) {
                layer.msg('正在上传中，请稍候', {icon: 2});
                return;
            }
            isUploading = true;
            
            var canvas = cropper.getCroppedCanvas();
            canvas.toBlob(function(blob) {
                var formData = new FormData();
                var fileNameParts = originalFileName.split('.');
                var fileExtension = fileNameParts.pop();
                var fileNameWithoutExtension = fileNameParts.join('.');
                var newFileName = fileNameWithoutExtension + '_' + generateRandomString(8) + '.' + fileExtension;
                
                formData.append('file', blob, newFileName);
                formData.append('cid', '{$cid}');

                fetch("{:siteUrl('common/upload/upload_one_filesystem')}?cid={$cid}", {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(result => {
                    isUploading = false;
                    if (result.result == 1) {
                        layer.msg('裁剪图片上传成功', {icon: 1});
                        setTimeout(function() {
                            window.parent.layer.close(window.parent.layer.getFrameIndex(window.name));
                        }, 1000);
                    } else {
                        layer.msg(result.msg || '上传失败', {icon: 2});
                    }
                })
                .catch(error => {
                    isUploading = false;
                    console.error('Error:', error);
                    layer.msg('上传过程中发生错误', {icon: 2});
                });
            }, 'image/jpeg', 0.9); // 添加质量参数
        });
    });
    </script>
</body>
</html>